package io.jpress.core.editorAddon;

import com.jfinal.core.Controller;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import io.jboot.utils.StrUtil;
import io.jboot.web.controller.JbootControllerContext;
import io.jboot.web.directive.annotation.JFinalDirective;

import java.util.Map;
import java.util.function.Function;

@JFinalDirective("editorAddons")
public class EditorAddonDirective extends BaseRenderDirective {

    @Override
    public void exec(Env env, Scope scope, Writer writer) {
        Controller controller = JbootControllerContext.get();
        Map<String, EditorAddonInfo> editorAddonInfoMap = EditorAddonManager.me().getEditorAddonInfoMap();
        for (EditorAddonInfo addon : editorAddonInfoMap.values()) {
            Function<Controller, Boolean> conditionFun = addon.getRenderCondition();
            if (conditionFun != null) {
                Boolean apply = conditionFun.apply(controller);
                //符合渲染条件，过滤掉
                if (apply != null && apply) {
                    doRenderAddon(env, scope, writer, addon);
                }
            }
            //不配置渲染条件，默认为全部渲染
            else {
                doRenderAddon(env, scope, writer, addon);
            }
        }
    }

    private void doRenderAddon(Env env, Scope scope, Writer writer, EditorAddonInfo addon) {
        if (StrUtil.isNotBlank(addon.getHtmlFile())) {
            exec(env, scope, writer, addon.getHtmlFile());
        }
    }
}
